package com.xyazm.order.statemachine.action.order.create;

import com.xyazm.common.enums.OrderStatusChangeEnum;
import com.xyazm.common.enums.OrderStatusEnum;
import com.xyazm.order.domain.builder.FullOrderData;
import com.xyazm.order.domain.dto.OrderInfoDTO;
import com.xyazm.order.domain.dto.SubOrderCreateDTO;
import com.xyazm.order.domain.param.CreateOrderParam;
import com.xyazm.order.statemachine.OrderStateMachine;
import com.xyazm.order.statemachine.StateMachineFactory;
import com.xyazm.order.statemachine.action.OrderStateAction;
import com.xyazm.process.engine.model.ProcessContextFactory;
import com.xyazm.process.engine.process.ProcessContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author xuyou
 * @date 2023年01月31日 20:37
 */
@Slf4j
@Component
public class OrderCreateAction extends OrderStateAction<CreateOrderParam> {

    @Resource
    private ProcessContextFactory processContextFactory;

    @Autowired
    private StateMachineFactory stateMachineFactory;



    @Override
    public OrderStatusChangeEnum event() {
        return OrderStatusChangeEnum.ORDER_CREATED;
    }


    @Override
    protected OrderInfoDTO onStateChangeInternal(OrderStatusChangeEnum event, CreateOrderParam context) {
        log.info("OrderCreateAction ...");
        // 获取流程引擎并执行
        ProcessContext masterOrderCreateProcess = processContextFactory.getContext("masterOrderCreateProcess");
        masterOrderCreateProcess.set("createOrderParam", context);
        masterOrderCreateProcess.start();

        // 流程执行完之后，获取返回参数
        Set<Integer> productTypeSet = masterOrderCreateProcess.get("productTypeSet");
        FullOrderData fullOrderData = masterOrderCreateProcess.get("fullMasterOrderData");
        OrderInfoDTO orderInfoDTO = masterOrderCreateProcess.get("orderInfoDTO");
        orderInfoDTO.setProductTypeSet(productTypeSet);
        orderInfoDTO.setFullOrderData(fullOrderData);
        return orderInfoDTO;
    }


    /**
     * 状态变更后置操作
     * @author xuyou
     * 2023-02-04 14:19
     * @param event
     * @param context
    */
    @Override
    protected void postStateChange(OrderStatusChangeEnum event, OrderInfoDTO context) {
        super.postStateChange(event, context);

        Set<Integer> productTypeSet = context.getProductTypeSet();
        FullOrderData fullOrderData = context.getFullOrderData();
        if (productTypeSet.size() <= 1) {
            return;
        }

        // 存在多种商品类型，需要按商品类型进行拆单
        for (Integer productType : productTypeSet) {
            // 通过状态机来生成子订单
            OrderStateMachine orderStateMachine = stateMachineFactory.getOrderStateMachine(OrderStatusEnum.NULL);
            orderStateMachine.fire(OrderStatusChangeEnum.SUB_ORDER_CREATED,
                    new SubOrderCreateDTO(fullOrderData, productType));
        }

    }
}
